package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.NEWLONGXIAAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author sdq
 * @Date 2022/9/1 18:05
 */
@Slf4j
@Service
public class NEWLONGXIAAPIImpl implements NEWLONGXIAAPI {
    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    private static String YX915URL = null;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        String path = "add";
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"add",salePartner);
        log.info("龙虾添加接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(salePartner.getOther() + path, params, null);
        log.info("龙虾游添加接口返回参数={}", response);
        JSONArray jsonArray = JSONArray.parseArray(response);
        String status = "";
        String resultJson = "";
        for(Object o : jsonArray){
            status = JSONObject.parseObject(o.toString()).getString("status");
            resultJson = JSONObject.parseObject(o.toString()).getString("errorMessage");
        }
        if (!"200".equals(status)) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecs.get(0).setOutid(resultJson.replace("商品添加成功,编号",""));
                artRecMapper.updateArtRec(artRecs.get(0));
            }else{
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRecreq.setType(LCConstant.interAdd);
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setSaleCode(salePartner.getSaleName());
                artRecreq.setOutid(resultJson.replace("商品添加成功,编号",""));
                artRecMapper.insertArtRec(artRecreq);
            }
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String path = "change";
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"update",salePartner);
        log.info("龙虾编辑接口请求参数={}", JSONObject.toJSONString(params));
//        String cover = MapUntils.getCover(params);
//        long timestamp = System.currentTimeMillis();
//        cover = cover+"timestamp="+timestamp+"&"+salePartner.getSaleKey();
//        String sign = DigestUtils.md5Hex(cover);
//        params.put("sign", sign);
        String response = HttpUtils.doPostForm(salePartner.getOther() + path, params, null);
        log.info("龙虾编辑接口返回参数={}", response);
        JSONArray jsonArray = JSONArray.parseArray(response);
        String status = "";
        String resultJson = "";
        for(Object o : jsonArray){
            status = JSONObject.parseObject(o.toString()).getString("status");
            resultJson = JSONObject.parseObject(o.toString()).getString("errorMessage");
        }
        if (!"200".equals(status)) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson);
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,String type, SalePartner salePartner) {

        Map<String,Object> params = new TreeMap<>();
        params.put("session", salePartner.getTwoOther());
        long timestamp = System.currentTimeMillis();
        params.put("timestamp",timestamp);
        if (goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")) {
            if(type.equals("add")) {
                params.put("openid", "476921188d272f66eb32a697bd06768b");
            }
            params.put("qu", goodsInfoAndAttrValueDto.getSystemName());
            params.put("fu", goodsInfoAndAttrValueDto.getCarrierName());
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("和平精英")){
            if(type.equals("add")) {
                params.put("openid", "0469e2c9725081649f776bafd54cd706");
            }
            params.put("qu", goodsInfoAndAttrValueDto.getSystemName());
            params.put("fu", goodsInfoAndAttrValueDto.getCarrierName());
        }else if (goodsInfoAndAttrValueDto.getGameName().contains("原神")){
            if(type.equals("add")) {
                params.put("openid", "8a5a0855bcfa0c09778337818ae22127");
            }
            params.put("qu", "全区");
            params.put("fu", "全服");
        }else if (goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")){
            if(type.equals("add")) {
                params.put("openid", "5c6215cda79a7609f0b11a0ef02332bc");
            }
            String qufu = "[{\"qu\":\"电信\",\"fu\":\"安徽一区&福建一区&广东一区&广东二区&广东三区&广东四区&湖北一区&湖北二区&湖南一区&湖南二区&江苏一区&江苏二区&南方大区&陕西一区&上海一区&上海二区&四川一区&四川二区&云南一区&浙江一区&浙江二区&重庆一区&江西一区&广西一区\"},{\"qu\":\"网通\",\"fu\":\"北方大区&北京一区&北京二区&北京三区&北京四区&河北一区&河南一区&河南二区&黑龙江区&吉林一区&辽宁一区&辽宁二区&辽宁三区&山东一区&山东二区&山西一区\"},{\"qu\":\"其他大区\",\"fu\":\"教育网专区&移动专区\"}]";
            JSONArray jsonArray = JSONArray.parseArray(qufu);
            for(Object o : jsonArray){
                String[] fus = JSONObject.parseObject(o.toString()).getString("fu").split("&");
                for(String s : fus){
                    if(goodsInfoAndAttrValueDto.getServerName().contains(s)){
                        params.put("qu", JSONObject.parseObject(o.toString()).getString("qu"));
                        params.put("fu", s);
                        break;
                    }
                }
            }
        }else if (goodsInfoAndAttrValueDto.getGameName().contains("英雄联盟")){
            if(type.equals("add")) {
                params.put("openid", "7b8020da2714a7cd5dda79ca24ea5caa");
            }
            String dianxin ="[{\"qu\":\"电信\",\"fu\":\"艾欧尼亚&暗影岛&班德尔城&裁决之地&钢铁烈阳&黑色玫瑰&教育网专区&巨神峰&均衡教派&祖安&卡拉曼达&雷瑟守备&诺克萨斯&皮城警备&皮尔特沃夫&守望之海&水晶之痕&影流&战争学院&征服之海\"},{\"qu\":\"网通\",\"fu\":\"比尔吉沃特&德玛西亚&弗雷尔卓德&无畏先锋&恕瑞玛&扭曲丛林&巨龙之巢\"},{\"qu\":\"体验服\",\"fu\":\"试练之地\"},{\"qu\":\"全网络大区\",\"fu\":\"男爵领域\"},{\"qu\":\"其他\",\"fu\":\"峡谷之巅\"}]";
            JSONArray jsonArray =  JSONArray.parseArray(dianxin);
            for(Object o : jsonArray){
                if(JSONObject.parseObject(o.toString()).getString("qu").contains("电信")||JSONObject.parseObject(o.toString()).getString("qu").contains("网通")){
                    String[] fus = JSONObject.parseObject(o.toString()).getString("fu").split("&");
                    for(String s : fus){
                        if(goodsInfoAndAttrValueDto.getServerName().contains(s)){
                            params.put("qu", JSONObject.parseObject(o.toString()).getString("qu"));
                            params.put("fu", s);
                            break;
                        }
                    }
                }else{
                    if(goodsInfoAndAttrValueDto.getServerName().contains(JSONObject.parseObject(o.toString()).getString("fu"))){
                        params.put("qu", JSONObject.parseObject(o.toString()).getString("qu"));
                        params.put("fu", JSONObject.parseObject(o.toString()).getString("fu"));
                        break;
                    }
                }
            }
        }else if (goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")){
            if(type.equals("add")) {
                params.put("openid", "59a3ae6746aec3ecad1d8c143ca9fe07");
            }
            params.put("qu", "全区");
            params.put("fu", "全服");
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("火影忍者")){
            if(type.equals("add")) {
                params.put("openid", "6264a518875b05579339dd20c3832c4c");
            }
            params.put("qu", "全区");
            params.put("fu", "全服");
        }
        params.put("sfcode", descTitle+"_"+goodsInfoAndAttrValueDto.getId());
        params.put("title",  "【"+descTitle+"_"+goodsInfoAndAttrValueDto.getId() + "】" +goodsInfoAndAttrValueDto.getDes().replace("+","加"));
        params.put("description", "【"+descTitle+"_"+goodsInfoAndAttrValueDto.getId() + "】" +goodsInfoAndAttrValueDto.getDes().replace("+","加"));
        params.put("number", goodsInfoAndAttrValueDto.getId());
        params.put("pass", goodsInfoAndAttrValueDto.getId());
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String image = "";
        if(infoImgs.size()>0){
            for(GoodsInfoImg infoImg1:infoImgs){
                image+=","+infoImg1.getImgUrl();
            }
        }else{
            image=","+ LCConstant.defaultImg;
        }
        params.put("image", image.substring(1));
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), salePartner.getSeleep());
        commonApi.setPrice(bigDecimal, goodsInfoAndAttrValueDto.getId(), salePartner);
        params.put("price",bigDecimal);
        params.put("ht","true");
        String cover = getCover(params);
        cover = cover+"timestamp="+timestamp+"&"+salePartner.getSaleKey();
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover);
        System.out.println(sign);
        params.put("sign", sign);
        System.out.println(params);
        return params;
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        String path = "delete";
        Map<String, Object> params = new TreeMap<>();
        Map<String, Object> result = new HashMap<>();
        params.put("session", sa.getTwoOther());
        params.put("sfcode", descTitle+"_"+goodsInfoAndAttrValueDto.getId());
        long timestamp = System.currentTimeMillis();
        params.put("timestamp", timestamp);
        String cover = getCover(params);
        cover = cover+"timestamp="+timestamp+"&"+sa.getSaleKey();
        String sign = DigestUtils.md5Hex(cover);
        System.out.println(sign);
        params.put("sign", sign);
        log.info("龙虾删除接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(sa.getOther() + path, params,null);
        log.info("龙虾删除接口返回参数={}", response);
        JSONArray jsonArray = JSONArray.parseArray(response);
        String status = "";
        String resultJson = "";
        for(Object o : jsonArray){
            status = JSONObject.parseObject(o.toString()).getString("status");
            resultJson = JSONObject.parseObject(o.toString()).getString("errorMessage");
        }
        if (!"200".equals(status)) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(sa.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecMapper.deleteArtRecById(artRecs.get(0).getId());
            }
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson);
        return AjaxResult.success(result);
    }

    public static String getCover(Map<String,Object> params){


        System.out.println("通过Map.keySet遍历key和value：");

        StringBuffer resut = new StringBuffer();

        for (String key : params.keySet()) {

            System.out.println("key= "+ key + " and value= " + params.get(key));
            if(key!="timestamp") {
                resut.append(key + "=" + params.get(key) + "&");
            }
        }
        return resut.toString();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, IOException {


//        ---获取游戏
        String yx = "http://api.longxiagame.com/s/yxname";
        Map<String,Object> params = new TreeMap<>();
//        Map<String,Object> head = new TreeMap<>();
        long timestamp = System.currentTimeMillis();
        params.put("session","aLuiL70nQVGFgo1u");
        params.put("timestamp",timestamp);
        System.out.println(timestamp);
        String cover = getCover(params);
        cover = cover+"timestamp="+timestamp+"&55f047d5afe6cffc191f8e0d496b3f6a";
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover);
        System.out.println(sign);
        params.put("sign", sign);
        System.out.println(params);
        String response = HttpUtils.doPostForm(yx,params,null);
        System.out.println(response);

//        String dianxin = "[{\\\"qu\\\":\\\"电信\\\",\\\"fu\\\":\\\"艾欧尼亚&暗影岛&班德尔城&裁决之地&钢铁烈阳&黑色玫瑰&教育网专区&巨神峰&均衡教派&祖安&卡拉曼达&雷瑟守备&诺克萨斯&皮城警备&皮尔特沃夫&守望之海&水晶之痕&影流&战争学院&征服之海\\\"},{\\\"qu\\\":\\\"网通\\\",\\\"fu\\\":\\\"比尔吉沃特&德玛西亚&弗雷尔卓德&无畏先锋&恕瑞玛&扭曲丛林&巨龙之巢\\\"},{\\\"qu\\\":\\\"体验服\\\",\\\"fu\\\":\\\"试练之地\\\"},{\\\"qu\\\":\\\"全网络大区\\\",\\\"fu\\\":\\\"男爵领域\\\"},{\\\"qu\\\":\\\"其他\\\",\\\"fu\\\":\\\"峡谷之巅\\\"}]\"";
//        String dianxin ="[{\"qu\":\"电信\",\"fu\":\"艾欧尼亚&暗影岛&班德尔城&裁决之地&钢铁烈阳&黑色玫瑰&教育网专区&巨神峰&均衡教派&祖安&卡拉曼达&雷瑟守备&诺克萨斯&皮城警备&皮尔特沃夫&守望之海&水晶之痕&影流&战争学院&征服之海\"},{\"qu\":\"网通\",\"fu\":\"比尔吉沃特&德玛西亚&弗雷尔卓德&无畏先锋&恕瑞玛&扭曲丛林&巨龙之巢\"},{\"qu\":\"体验服\",\"fu\":\"试练之地\"},{\"qu\":\"全网络大区\",\"fu\":\"男爵领域\"},{\"qu\":\"其他\",\"fu\":\"峡谷之巅\"}]";
//        JSONArray jsonArray =  JSONArray.parseArray(dianxin);
//        for(Object o : jsonArray){
//            System.out.println(JSONObject.parseObject(o.toString()));
//        }
    }


}

